<?php

namespace app\admin\controller\cms;

use app\common\controller\AdminBaseController;
use app\common\model\cms\MoudleModel;
use app\common\traits\adminTraits;
use think\facade\Env;
use think\helper\Str;

class MoudleController extends AdminBaseController {
    use adminTraits;

    /*
     * 初始化
     */
    public function __construct() {
        parent::__construct();
        $this->model = new MoudleModel();
    }

    /**
     * 设置文件路径
     * @return array
     */
    private function getPath($info){
        $studlyName = Str::studly(str_replace('cms_','',$info['table_name'])); //TableArticle
        $tplName = strtolower(str_replace('cms_table_','',$info['table_name']));
        $path = [
            'model'=>Env::get('APP_PATH').'/common/model/cms/'.$studlyName.'Model.php',
            'add'=>Env::get('APP_PATH').'/admin/view/cms/content/'.$tplName.'_add.php',
            'edit'=>Env::get('APP_PATH').'/admin/view/cms/content/'.$tplName.'_edit.php',
            'list'=>Env::get('APP_PATH').'/admin/view/cms/content/'.$tplName.'_list.php',
        ];
        return $path;
    }
    /**
     * 初始化代码
     */
    public function initCode(){
        $id=$this->request->param('id/d');
        $type = $this->request->param('type');
        $code = '';
        if(in_array($type,['add','edit'])){
            $code = $this->model->initForm($id,$type);
        }
        if($type=='model'){
            $code = $this->model->initModel($id);
        }
        if($type=='list'){
            $code = $this->model->initList();
        }
        return $code;
    }
    /**
     * 修改对应模板
     * @return mixed
     */
    public function viewtpl() {
        $id = $this->request->param('id/d');
        $type = $this->request->param('type');
        $info = $this->model->where('id',$id)->find();
        $path = $this->getPath($info);
        if($this->request->isAjax()){
            try{
                $tpl = $this->request->param('tpl');
                if(empty($tpl)) exception('代码不能为空！');
                $tpl = str_replace('\\','\\\\',$tpl);
                file_put_contents($path[$type],html_out($tpl));
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('保存成功！');
        }
        $info['tpl']='';
        if(file_exists($path[$type])){ //存在
            $info['tpl'] = file_get_contents($path[$type]);
        }
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 刷新缓存
     */
    public function refresh() {
        try {
            $this->model->updateCache();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }
}